const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const AdmZip = require('adm-zip');
const translate = require('@vitalets/google-translate-api').translate;

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    icon: path.join(__dirname, 'build/icon.png'),
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    },
    show: false
  });

  // 添加应用菜单
  const menu = [
    {
      label: '文件',
      submenu: [
        {
          label: '打开文件夹',
          accelerator: 'CmdOrCtrl+O',
          click: () => {
            mainWindow.webContents.send('menu-open-directory');
          }
        },
        { type: 'separator' },
        { role: 'quit', label: '退出' }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { role: 'undo', label: '撤销' },
        { role: 'redo', label: '重做' },
        { type: 'separator' },
        { role: 'cut', label: '剪切' },
        { role: 'copy', label: '复制' },
        { role: 'paste', label: '粘贴' },
        { type: 'separator' },
        { role: 'selectAll', label: '全选' }
      ]
    },
    {
      label: '视图',
      submenu: [
        { role: 'reload', label: '刷新' },
        { role: 'toggleDevTools', label: '开发者工具' },
        { type: 'separator' },
        { role: 'resetZoom', label: '重置缩放' },
        { role: 'zoomIn', label: '放大' },
        { role: 'zoomOut', label: '缩小' },
        { type: 'separator' },
        { role: 'togglefullscreen', label: '全屏' }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            dialog.showMessageBox(mainWindow, {
              type: 'info',
              title: '关于 Log Viewer',
              message: 'Log Viewer v1.0.0',
              detail: '一个用于查看Android应用日志的桌面工具\n\n© 2023 Log Viewer',
              buttons: ['确定']
            });
          }
        }
      ]
    }
  ];
  
  const { Menu } = require('electron');
  Menu.setApplicationMenu(Menu.buildFromTemplate(menu));

  mainWindow.loadFile('index.html');
  
  // 窗口准备好后显示，避免白屏
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });
  
  // 开发时打开开发者工具
  // mainWindow.webContents.openDevTools();

  mainWindow.on('closed', function () {
    mainWindow = null;
  });
}

app.whenReady().then(createWindow);

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', function () {
  if (mainWindow === null) createWindow();
});

// 处理文件夹拖放
ipcMain.on('open-directory-dialog', (event) => {
  dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  }).then(result => {
    if (!result.canceled) {
      event.reply('selected-directory', result.filePaths[0]);
    }
  }).catch(err => {
    console.log(err);
  });
});

// 读取目录结构
ipcMain.handle('read-directory', async (event, dirPath) => {
  try {
    const structure = await readDirectoryStructure(dirPath);
    return structure;
  } catch (error) {
    console.error('Error reading directory:', error);
    return { error: error.message };
  }
});

// 读取文件内容
ipcMain.handle('read-file', async (event, filePath) => {
  try {
    // 获取文件状态以检查文件大小
    const stats = await fs.promises.stat(filePath);
    const fileSizeInBytes = stats.size;
    
    // 设置大文件阈值（5MB）
    const MAX_FILE_SIZE = 5 * 1024 * 1024;
    
    // 如果文件太大，只读取前面部分
    if (fileSizeInBytes > MAX_FILE_SIZE) {
      console.log(`文件过大 (${(fileSizeInBytes / 1024 / 1024).toFixed(2)} MB)，只读取前 ${(MAX_FILE_SIZE / 1024 / 1024).toFixed(2)} MB`);
      
      // 创建可读流并只读取部分内容
      const fileStream = fs.createReadStream(filePath, { 
        encoding: 'utf8',
        start: 0,
        end: MAX_FILE_SIZE - 1
      });
      
      // 收集数据块
      let content = '';
      for await (const chunk of fileStream) {
        content += chunk;
      }
      
      // 添加文件过大的提示
      content += `\n\n[文件过大，仅显示前 ${(MAX_FILE_SIZE / 1024 / 1024).toFixed(2)} MB 内容]`;
      return content;
    } else {
      // 文件大小合适，完整读取
      const content = await fs.promises.readFile(filePath, 'utf8');
      return content;
    }
  } catch (error) {
    console.error('Error reading file:', error);
    return { error: error.message };
  }
});

// 处理翻译请求
ipcMain.handle('translate-text', async (event, { text, from = 'auto', to = 'zh-CN' }) => {
  try {
    console.log(`翻译请求: 从 ${from} 到 ${to}, 文本: ${text.substring(0, 50)}${text.length > 50 ? '...' : ''}`);
    const result = await translate(text, { from, to });
    console.log(`翻译成功: ${result.text.substring(0, 50)}${result.text.length > 50 ? '...' : ''}`);
    return result;
  } catch (error) {
    console.error('翻译错误:', error);
    throw error;
  }
});

// 处理ZIP文件
ipcMain.handle('process-zip-file', async (event, zipFilePath) => {
  try {
    // 创建临时目录用于解压文件
    const tempDir = path.join(os.tmpdir(), 'logviewer_' + Date.now());
    
    // 确保临时目录存在
    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir, { recursive: true });
    }
    
    // 解压ZIP文件
    const zip = new AdmZip(zipFilePath);
    zip.extractAllTo(tempDir, true);
    
    console.log(`ZIP文件已解压到: ${tempDir}`);
    
    // 读取解压后的目录结构
    const structure = await readDirectoryStructure(tempDir);
    
    return {
      structure,
      extractPath: tempDir
    };
  } catch (error) {
    console.error('处理ZIP文件时出错:', error);
    return { error: error.message };
  }
});

// 递归读取目录结构
async function readDirectoryStructure(dirPath) {
  const items = await fs.promises.readdir(dirPath, { withFileTypes: true });
  const structure = [];

  for (const item of items) {
    const itemPath = path.join(dirPath, item.name);
    if (item.isDirectory()) {
      const children = await readDirectoryStructure(itemPath);
      structure.push({
        name: item.name,
        path: itemPath,
        type: 'directory',
        children
      });
    } else {
      structure.push({
        name: item.name,
        path: itemPath,
        type: 'file',
        extension: path.extname(item.name).toLowerCase()
      });
    }
  }

  return structure;
}